/*
 * @Author: xiaosihan
 * @Date: 2024-11-23 22:49:44
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-12-01 01:06:58
 */

import { DesignData, GoodsData } from '#/type';
import userDesignService from '@/api/services/userDesignService';
import designDataHistory from '@/editorComponent/designDataHistory';
import designEditor from '@/editorComponent/designEditor';
import editorStore from '@/editorComponent/editorStore';
import preview3DRenderer from '@/editorComponent/preview3DRenderer';
import textureManager from '@/editorComponent/textureManager';
import goodsUtils from '@/utils/goodsUtils';
import { cloneDeep, isString } from 'lodash';

// 设置编辑器的数据
export default async function setEditorDate(ppid?: number, design_Data?: DesignData) {

  editorStore.setLoadding(true);
  let { color, colorValue, designData, ppId, previewThumb, thumbs, printArea, threadColor } = design_Data || {};

  const id = ppid || ppId || (await userDesignService.getDefaultDesignId());

  console.log('init editor');
  let goods_data: GoodsData = await userDesignService.getDesignById(id);

  goods_data = goodsUtils.tojson(goods_data);

  // 如果是字符串就转json
  if (isString(designData)) {
    designData = JSON.parse(designData);
  }
  if (isString(previewThumb)) {
    previewThumb = JSON.parse(previewThumb);
  }
  if (isString(thumbs)) {
    thumbs = JSON.parse(thumbs);
  }

  // 保持设计数据的完整性
  let design_data: DesignData = {
    color: color || '白色',
    colorValue: colorValue || `#ffffff`,
    designData: designData || {},
    ppId: ppId || goods_data.id,
    previewThumb: previewThumb || [],
    thumbs: thumbs || [],
    printArea: printArea || 'front',
    threadColor: threadColor || '#ffffff',
  }

  //删除当前衣服没有的部位
  for (let c in design_data.designData) {
    if (!goods_data.component.map((c) => c.key).includes(c)) {
      delete design_data.designData[c];
    }
  }

  goods_data.component.map((c) => {
    design_data.designData[c.key] = design_data.designData[c.key] || {
      objects: [],
      version: '5.3.0',
      background: '#ffffff',
    };
  });
  // 临时保存历史记录
  designDataHistory.setStashData(design_data.designData);
  // 设置设计数据
  editorStore.setDesignData(design_data);
  //设置历史记录数据的id
  designDataHistory.store.setId(id);
  // 初始化所有遮罩
  await designEditor.initFabricMarkMap(goods_data);
  // 初始化全部纹理
  await textureManager.init(design_data.designData);
  //3d模型渲染器
  await preview3DRenderer.loadCloth(goods_data.modelUrl);
  // 设置商品数据
  editorStore.setGoodsData(goods_data);
  // 初始完成是记录一次历史数据
  designDataHistory.recordHistory();

  //加载结束
  editorStore.setLoadding(false);

}
